
package cn.com.pusai.core.util;


public class ByteUtil
{

	public ByteUtil()
	{
	}

	public static byte[] toByte(long n)
	{
		byte buf[] = new byte[8];
		buf[0] = (byte)(int)(n >> 56);
		buf[1] = (byte)(int)(n >> 48);
		buf[2] = (byte)(int)(n >> 40);
		buf[3] = (byte)(int)(n >> 32);
		buf[4] = (byte)(int)(n >> 24);
		buf[5] = (byte)(int)(n >> 16);
		buf[6] = (byte)(int)(n >> 8);
		buf[7] = (byte)(int)n;
		return buf;
	}
	
	
	public static long toLong(byte b[])
	{
		return toLong(b, 0);
	}

	public static long toLong(byte b[], int offset)
	{
		offset += 7;
		return (long)(b[offset--] & 0xff | (b[offset--] & 0xff) << 8 | (b[offset--] & 0xff) << 16 | (b[offset--] & 0xff) << 24 | (b[offset--] & 0xff) << 32 | (b[offset--] & 0xff) << 40 | (b[offset--] & 0xff) << 48 | (b[offset--] & 0xff) << 56);
	}

	public static byte[] toByte(int n)
	{
		byte buf[] = new byte[4];
		buf[0] = (byte)(n >> 24);
		buf[1] = (byte)(n >> 16);
		buf[2] = (byte)(n >> 8);
		buf[3] = (byte)n;
		return buf;
	}

	public static int toInt(byte b[], int offset)
	{
		offset += 3;
		return b[offset--] & 0xff | (b[offset--] & 0xff) << 8 | (b[offset--] & 0xff) << 16 | (b[offset--] & 0xff) << 24;
	}

	public static int toInt(byte b[])
	{
		if (b.length == 1)
			return b[0];
		else
			return toInt(b, 0);
	}

	public static byte[] byteContact(byte bs[][])
	{
		int total = 0;
		byte abyte0[][];
		int j = (abyte0 = bs).length;
		for (int i = 0; i < j; i++)
		{
			byte b[] = abyte0[i];
			if (b != null)
				total += b.length;
		}

		byte buf[] = new byte[total];
		int positon = 0;
		byte abyte1[][];
		int l = (abyte1 = bs).length;
		for (int k = 0; k < l; k++)
		{
			byte b[] = abyte1[k];
			if (b != null)
			{
				System.arraycopy(b, 0, buf, positon, b.length);
				positon += b.length;
			}
		}

		return buf;
	}

	public static String byteToHex(byte data[])
	{
		StringBuilder sb = new StringBuilder(data.length * 2);
		for (int i = 0; i < data.length; i++)
		{
			sb.append(Integer.toHexString((0xf0 & data[i]) >>> 4));
			sb.append(Integer.toHexString(0xf & data[i]));
		}

		return new String(sb);
	}

	public static byte[] hexToByte(String hexData)
	{
		byte data[] = new byte[hexData.length() / 2];
		for (int i = 0; i < data.length; i++)
			data[i] = (byte)Integer.parseInt(hexData.substring(2 * i, 2 * i + 2), 16);

		return data;
	}
}
